﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;


namespace LiveProjectManager.DDD.Services
{
    public class PostCommentService : Base.Service<Domains.PostComment>
    {
        public PostCommentService() : base()
        {
        }


        override public ICollection<Domains.PostComment> getAll(int paginateBy = 0, int page = 1)
        {
            if (paginateBy > 0)
            {
                if (page <= 0)
                    page = 1;
                return (from pc in _repository orderby pc.Id select pc).Skip(paginateBy * (page - 1)).Take(paginateBy).ToList();
            }
            return (from pc in _repository orderby pc.Id select pc).ToList();
        }


        public ICollection<Domains.PostComment> getAllByPost(Domains.Post myPost, int paginateBy = 0, int page = 1)
        {
            if (paginateBy != 0)
                return (from pc in _repository where pc.Post.Id == myPost.Id orderby pc.CreatedOn select pc)
                    .Skip(paginateBy * (page - 1))
                    .Take(paginateBy).ToList();
            return (from pc in _repository where pc.Post.Id == myPost.Id orderby pc.CreatedOn select pc).ToList();
        }


        override public Domains.PostComment getById(long myId)
        {
            ICollection<Domains.PostComment> myResults = (from pc in _repository 
                                                          where pc.Id == myId select pc).ToList();
            return (myResults.Count != 1) ? null : myResults.First();
        }


        public bool create(string myContent, Domains.User mySender, Domains.Post myPost, bool autoSave = true)
        {
            try {
                if (myContent.Length == 0)
                    return false;
                Domains.PostComment myNewPostComment = new Domains.PostComment
                {
                    Post = myPost,
                    Content = myContent,
                    User = mySender
                };
                myNewPostComment.CreatedOn = DateTime.Now;
                _repository.Add(myNewPostComment);
                if (autoSave)
                    _context.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        override public bool remove(long myId, bool autoSave = true)
        {
            Domains.PostComment myPostComment = getById(myId);
            if (myPostComment == null)
                return false;
            _repository.Remove(myPostComment);
            if (autoSave)
                _context.SaveChanges();
            return true;
        }
    }
}